package net.loyin.app.ctrl.admin;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.tx.Tx;
import net.loyin.annotation.ControllerBind;
import net.loyin.annotation.CtrlMethod;
import net.loyin.app.model.SysRole;
import net.loyin.app.model.SysUser;
import net.loyin.utils.encrypt.DESUtils;
import org.apache.commons.lang.StringUtils;

import java.util.*;

/**
 * 用户
 * Created by loyin on 16/1/12.
 */
@ControllerBind(route = "/admin/sysUser")
public class SysUserCtrl extends AdminBaseCtrl {

    public void index(){
        String kwd=this.getPara("kwd");
        int pageNumber=this.getParaToInt("pageNumber",1);
        int pageSize=this.getParaToInt("pageSize",20);
        List<Object> paras=new ArrayList<Object>();
        StringBuffer sql=new StringBuffer("select * from ");
        sql.append(SysUser.tableName);
        sql.append(" u where 1=1 ");
        if(StringUtils.isNotBlank(kwd)){
            sql.append(" and (u.account like ? or u.email like ? or u.realname like ?)");
            kwd="%"+kwd+"%";
            paras.add(kwd);
            paras.add(kwd);
            paras.add(kwd);
        }
        Integer status=this.getParaToInt("status");
        if(status!=null){
            sql.append(" and u.status=? ");
            paras.add(status);
        }
        this.keepPara();
        this.setAttr("page",SysUser.dao.paginate(pageNumber,pageSize,sql.toString(),paras.toArray()));
    }
    public void add(){
        String id=this.getPara(0);
        if(StringUtils.isNotBlank(id)){
            this.setAttr("po",SysUser.dao.findById(id));
            this.setAttr("userRoleList",SysUser.dao.qryUserRoles(id));
        }
        this.setAttr("roleList", SysRole.dao.find("select id,name from sys_role where status=1 order by name"));
    }
    /**个人信息*/
    public void profile(){

    }/**保存个人信息*/
    public void saveProfile(){
        SysUser entity=this.getModel(SysUser.class);
        if(entity!=null){
            entity.remove("password","status","create_datetime");//移除敏感字段
            entity.setId(this.getUserId());
            try {
                entity.update();
            }catch (Exception e){
                logger.debug("保持个人信息异常!",e);
                this.renderJsonMsg(JSON_RESULT_ERROR,"保持个人信息异常!");
            }
        }else{
            this.renderJsonMsg(JSON_RESULT_WARNNING,"提交参数错误!");
        }
    }
    @Before(Tx.class)
    @CtrlMethod(isAjax = true)
    public void save(){
        SysUser entity=this.getModel(SysUser.class);
        if(entity!=null){
            String id=entity.getId();
            String account=entity.getAccount();
            String email=entity.getEmail();
            String password=entity.getPassword();
            if(StringUtils.isNotBlank(account)){
                if(SysUser.dao.checkAccount(account,id)==false){//存在账号
                    this.renderJsonMsg(JSON_RESULT_WARNNING,"账号"+account+"已经存在!请更改为其他的!");
                    return;
                }
            }
            if(StringUtils.isNotBlank(email)){
                if(SysUser.dao.checkEmail(email,id)==false){//存在账号
                    this.renderJsonMsg(JSON_RESULT_WARNNING,email+"已经存在!请更改为其他的!");
                    return;
                }
            }else{
                this.renderJsonMsg(JSON_RESULT_WARNNING,"账号必填");
                return;
            }
            if(StringUtils.isNotBlank(password)){ //加密密码
                entity.setPassword(DESUtils.me.encryptString(password));
            }
            if(StringUtils.isEmpty(id)) {
                entity.save();
            }else{
                if(StringUtils.isEmpty(password)){
                    entity.remove("password");
                }
                entity.update();
            }
            id=entity.getId();
            SysUser.dao.cfgRole(id,this.getParaValues("roleList"));
            this.renderJsonMsg(JSON_RESULT_SUCCESS,"保存成功!");
        }else{
            this.renderJsonMsg(JSON_RESULT_WARNNING,"参数错误!");
        }
    }
    @CtrlMethod(isAjax = true)
    public void del(){
        String id=this.getPara(0);
        try {
            if (StringUtils.isNotBlank(id)) {
                SysUser.dao.deleteById(id);
                this.renderJsonMsg(JSON_RESULT_SUCCESS, "删除成功!");
            } else {
                this.renderJsonMsg(JSON_RESULT_WARNNING, "缺少参数!");
            }
        }catch (Exception e){
            logger.error("删除异常",e);
            this.renderJsonMsg(JSON_RESULT_ERROR, "删除异常,可能存在引用,请先删除对应的数据!");
        }
    }
}
